#!/bin/bash

base_uri="http://webdav.data.aad.gov.au/metadata/iso-ands/"

trapFunction () {
  echo Exiting
}

read -p "Do you want to retrieve content from the web before transforming -'Y' for yes ('N' will transform only)?  " choice
echo    # (optional) move to a new line
if [[ $choice =~ ^[Yy]$ ]]
then
  rm ForAAD/ISO/*.xml
  echo Retrieving content from the web
  rm link_list.out
  wget --quiet -O - $base_uri | grep -oP '(?<=href=")[^"]*(?=")' >> link_list.out

  trap "exit" INT
  while read link; do

    if [ ${link: -4} == ".xml" ]
    then 

      if [ ${link} != "AAD_RIFCS_ISO.xml" ]
      then

        uri=$base_uri$link
        echo $uri 

        link_no_extension=${link%.*}
        echo $link_no_extension

        wget --header='Accept-Language: en-us' $uri -O ForAAD/ISO/${link_no_extension}_ISO.xml
        
      fi
    
    fi
    
  done < link_list.out

fi

rm ForAAD/RifCs/AAD_RegistryObjects.xml
rm ForAAD/RifCs/*.xml

echo '<registryObjects xmlns:xs="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns="http://ands.org.au/standards/rif-cs/registryObjects"
                 xsi:schemaLocation="http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/schema/registryObjects.xsd">' >> ForAAD/RifCs/AAD_RegistryObjects.xml

trap trapFunction EXIT
trap 'exit 127' INT

ls "/home/anucsiro/workspace/XML/ShellScripts/ForAAD/ISO" | while read f; do
    fileNamePath="/home/anucsiro/workspace/XML/ShellScripts/ForAAD/ISO/""$f"
    fileNameNoExtension=${f%.*}
    echo File: $fileNamePath
    echo Transforming $fileNamePath
    echo java -jar /home/anucsiro/workspace/XML/XSLT/saxon9he.jar "/home/anucsiro/workspace/XML/ShellScripts/ForAAD/ISO/""$f" /home/anucsiro/workspace/XML/XSLT/ISO19139_To_RIFCS/AAD/AAD_rif_in_progress.xsl > /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    java -jar /home/anucsiro/workspace/XML/XSLT/saxon9he.jar \
        "/home/anucsiro/workspace/XML/ShellScripts/ForAAD/ISO/""$f" \
        /home/anucsiro/workspace/XML/XSLT/ISO19139_To_RIFCS/AAD/AAD_rif_in_progress.xsl \
        > /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    echo XML written to /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml"

    cat /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" >> /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/AAD_RegistryObjects.xml
   
done

echo '</registryObjects>' >> /home/anucsiro/workspace/XML/ShellScripts/ForAAD/RifCs/AAD_RegistryObjects.xml






